package com.wangsd.web.face.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.domain.AlipayTradeRefundApplyModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.binarywang.wxpay.bean.request.WxPayOrderQueryRequest;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundQueryResult;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.wangsd.common.component.WeixinPayService;
import com.wangsd.common.component.WxPayServiceExt;
import com.wangsd.common.component.extBean.*;
import com.wangsd.common.exception.BusinessException;
import com.wangsd.common.mq.MqSend;
import com.wangsd.common.tyt.tytBean.TytMicropayRequest;
import com.wangsd.common.tyt.tytBean.TytMicropayResponse;
import com.wangsd.common.tyt.tytBean.TytOrderQueryRequest;
import com.wangsd.common.utils.*;
import com.wangsd.web.face.entity.*;
import com.wangsd.web.face.entity.Receiver;
import com.wangsd.web.face.mapper.DepositMapper;
import com.wangsd.web.face.mapper.TOrderMapper;
import com.wangsd.web.face.service.*;
import com.wangsd.web.miniapp.entity.WxPay;
import com.wangsd.web.sys.entity.SysUser;
import com.wangsd.web.sys.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.wangsd.common.utils.PayUtil.getIpAddr;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author generator
 * @since 2019-09-23
 */
@Service
@Slf4j
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements TOrderService {

    @Value("${service.url}")
    private String notifyUrl;

    @Value("${service.tyt.url}")
    private String tytUrl;
    @Resource
    TOrderMapper tOrderMapper;
    @Autowired
    MerchantService merchantService;
    @Autowired
    WeixinPayService weixinPayService;
    @Autowired
    DeviceService deviceService;
    @Autowired
    StoreService storeService;
    @Autowired
    MqSend mqSend;
    @Autowired
    ReceiveRecordService receiveRecordService;
    @Autowired
    ReceiverService receiverService;
    @Autowired
    MemberService memberService;
    @Autowired
    CloseAccountService closeAccountService;
    @Autowired
    ServiceBusinessService serviceBusinessService;
    @Autowired
    RefundRecordService refundRecordService;
    @Autowired
    TradeNoService tradeNoService;
    @Autowired
    SysUserService sysUserService;
    @Resource
    DepositMapper depositMapper;

    @Override
    @Transactional
    public void updateOrderByOutTradeNo(TOrder order) {
        QueryWrapper<TOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("out_trade_no", order.getOutTradeNo());
        tOrderMapper.update(order, queryWrapper);
    }

    @Override
    public TOrder createFacePayOrder(String faceCode, String deviceNo, Integer totalFee, Integer memberFee, String phone, String outTradeNo, Long storeUserId) throws Exception {
        try {
            //获取设备信息
            Device device = deviceService.selectByDeviceNo(deviceNo);
            //获取门店信息
            Store store = storeService.getById(device.getStoreId());
            //获取商户信息
            Merchant merchant = merchantService.getById(store.getMerchantId());

            String merchantCode = merchant.getCode();
            String[] codes = merchantCode.split("-");
            Long serviceId = Long.valueOf(codes[0]);//服务商ID
            Long agentId = Long.valueOf(codes[1]);//代理商ID

            String tradeType = "FACEPAY";
            if (StringUtils.isBlank(outTradeNo)) {
                outTradeNo = tradeNoService.getTradeNo();
                //outTradeNo = device.getId() + System.currentTimeMillis() + ApplicationUtils.getRandomStr(5);
                tradeType = "SWEPT";
            }
            //初始化支付service
            WxPayServiceExt wxPayService = weixinPayService.getServiceExt(merchant.getCode(), merchant.getSubMchId());

            WxPayMicropayRequestExt wxPayMicropayRequest = new WxPayMicropayRequestExt();
            wxPayMicropayRequest.setBody(store.getName() + "购买商品");
            wxPayMicropayRequest.setOutTradeNo(outTradeNo);
            //如果存在会员价，优先使用会员价
            wxPayMicropayRequest.setTotalFee((memberFee != null && memberFee > 0) ? memberFee : totalFee);
            wxPayMicropayRequest.setSpbillCreateIp("127.0.0.1");
            wxPayMicropayRequest.setAuthCode(faceCode);
            wxPayMicropayRequest.setSubAppId(merchant.getSubAppId());

            //attach携带会员电话
            if (StringUtils.isNotBlank(phone)) {//会员电话
                wxPayMicropayRequest.setAttach(phone);
            }

            if (merchant.getMinimumDraw() <= totalFee//达到抽成的最低金额
                    && merchant.getDrawFee() < merchant.getDrawTotalFee()) {//已抽成金额小于抽成总金额
                wxPayMicropayRequest.setProfitSharing("Y");
            }

            WxPayMicropayResultExt micropay = wxPayService.micropayExt(wxPayMicropayRequest);
            if (WxPayConstants.ResultCode.FAIL.equals(micropay.getReturnCode())) {
                throw new Exception("订单支付失败");
            }

            if (WxPayConstants.ResultCode.SUCCESS.equals(micropay.getReturnCode()) //扫码支付请求成功
                    && micropay.getResultCode().equals(WxPayConstants.ResultCode.SUCCESS)) {//返回结果集成功

                TOrder order = new TOrder();
                //服务商，代理商，商户，门店信息
                order.setBusinessServiceId(serviceId);
                order.setAgentId(agentId);
                order.setMerchantId(merchant.getId());
                order.setMerchantName(merchant.getName());
                order.setStoreId(store.getId());
                order.setStoreName(store.getName());
                order.setCode(store.getCode());

                order.setOrderTotalFee(Long.valueOf(totalFee));
                order.setOutTradeNo(outTradeNo);
                order.setPayType(1);
                order.setProfitSharing(StringUtils.isBlank(wxPayMicropayRequest.getProfitSharing()) ? "N" : wxPayMicropayRequest.getProfitSharing());
                order.setProfitSharingStatus(0);
                order.setTradeType(tradeType);//人脸支付
                order.setOrderStatus(1);
                order.setTimeEnd(micropay.getTimeEnd());
                //支付信息
                order.setTransactionId(micropay.getTransactionId());
                order.setOpenid(micropay.getOpenid());
                order.setDeviceNo(deviceNo);
                SysUser sysUser = sysUserService.getById(storeUserId);
                if (sysUser != null) {
                    order.setOrderCreateUserName(sysUser.getUsername());
                }
                //店员信息
                order.setStoreUserId(storeUserId);
                order.setRealPayFee((long) micropay.getCashFee());
                order.setTimeEnd(micropay.getTimeEnd());
                //会员价格
                order.setMemberTotalFee(memberFee != null ? Long.valueOf(memberFee) : Long.valueOf(totalFee));
                order.setSettlementTotalFee(micropay.getSettlementTotalFee() == null || micropay.getSettlementTotalFee() == 0 ? order.getMemberTotalFee() : Long.valueOf(micropay.getSettlementTotalFee()));
                order.setCouponFee(micropay.getCouponFee() == null || micropay.getCouponFee() == 0 ? 0L : Long.valueOf(micropay.getCouponFee()));

                if (StringUtils.isNotBlank(micropay.getAttach())) {//会员电话
                    order.setPhone(micropay.getAttach());
                }
                order.setUpdatedTime(new Date());
                //保存订单信息
                tOrderMapper.insert(order);

                //是否关注
                Integer isSend = StringUtils.isNotBlank(micropay.getSubIsSubscribe()) && micropay.getSubIsSubscribe().equals("Y") ? 2
                        : StringUtils.isNotBlank(micropay.getIsSubscribe()) && micropay.getIsSubscribe().equals("Y") ? 1 : 0;


                //发送店员收款消息推送
                storeService.sendWxTempLateReceivables(order);

                mqSend.sendCheckIsMember(merchant.getId(), micropay.getOpenid(), micropay.getSubOpenid(), micropay.getAttach(), isSend, order.getId(), "WXPAY");

                return order;
                //队列执行查询订单
                // mqSend.sendOrderQuery(order.getId());
            } else {
                //用户支付中
                if (micropay.getResultCode().equals(WxPayConstants.ResultCode.FAIL)
                        && micropay.getErrCode().equals("USERPAYING")) {
                    TOrder order = new TOrder();
                    //服务商，代理商，商户，门店信息
                    order.setBusinessServiceId(serviceId);
                    order.setAgentId(agentId);
                    order.setMerchantName(merchant.getName());
                    order.setMerchantId(merchant.getId());
                    order.setStoreId(store.getId());
                    order.setStoreName(store.getName());
                    order.setCode(store.getCode());

                    order.setOrderTotalFee(Long.valueOf(totalFee));
                    //会员价格
                    order.setMemberTotalFee(memberFee != null ? Long.valueOf(memberFee) : Long.valueOf(totalFee));

                    order.setOutTradeNo(outTradeNo);
                    order.setPayType(1);
                    order.setProfitSharing(StringUtils.isBlank(wxPayMicropayRequest.getProfitSharing()) ? "N" : wxPayMicropayRequest.getProfitSharing());
                    order.setProfitSharingStatus(0);
                    order.setTradeType(tradeType);//人脸支付
                    order.setOrderStatus(0);
                    order.setTimeEnd(micropay.getTimeEnd());
                    //支付信息
                    order.setTransactionId(micropay.getTransactionId());
                    order.setOpenid(micropay.getOpenid());
                    order.setDeviceNo(deviceNo);

                    //店员信息
                    order.setStoreUserId(storeUserId);
                    //保存订单信息
                    tOrderMapper.insert(order);

                    Thread.sleep(3000);
                    return this.queryOrderStatus(order, 1);

                } else {
                    throw new Exception("订单支付失败");
                }
            }
        } catch (WxPayException e) {
            e.printStackTrace();
            throw new Exception(StringUtils.isBlank(e.getErrCodeDes()) ? e.getReturnMsg() : e.getErrCodeDes());
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("订单支付失败");
        }
    }

    @Override
    @Transactional
    public TOrder createFaceDepositPayOrder(HttpServletRequest request, String faceCode, String deviceNo,
                                            String outTradeNo, Integer consumeFee,
                                            Integer depositFee, Long storeUserId, String subOpenId) throws Exception {
        try {
            //获取设备信息
            Device device = deviceService.selectByDeviceNo(deviceNo);
            //获取门店信息
            Store store = storeService.getById(device.getStoreId());
            //获取商户信息
            Merchant merchant = merchantService.getById(store.getMerchantId());

            String merchantCode = merchant.getCode();
            String[] codes = merchantCode.split("-");
            Long agentId = Long.valueOf(codes[1]);//代理商ID
            Long serviceId = Long.valueOf(codes[0]);//服务商ID

            //初始化支付service
            WxPayServiceExt wxPayService = weixinPayService.getServiceExt(merchant.getCode(), merchant.getSubMchId());

            DepositFacePayRequest depositFacePayRequest = new DepositFacePayRequest();
            depositFacePayRequest.setBody(store.getName() + "刷脸支付");
            depositFacePayRequest.setOutTradeNo(outTradeNo);
            depositFacePayRequest.setTotalFee(consumeFee + depositFee);
            String ipAddr = getIpAddr(request);
            depositFacePayRequest.setSpbillCreateIp(ipAddr);
            depositFacePayRequest.setFaceCode(faceCode);
            depositFacePayRequest.setDeposit("Y");
            depositFacePayRequest.setFeeType("CNY");
            depositFacePayRequest.setOpenid(subOpenId);
            depositFacePayRequest.setSignType(WxPayConstants.SignType.HMAC_SHA256);
            depositFacePayRequest.setSubAppId(merchant.getSubAppId());

            DepositFacePayResponse depositfacepay = wxPayService.depositfacepay(depositFacePayRequest);
            if (WxPayConstants.ResultCode.FAIL.equals(depositfacepay.getReturnCode())) {
                throw new Exception("押金支付失败");
            }

            if (WxPayConstants.ResultCode.SUCCESS.equals(depositfacepay.getReturnCode()) //扫码支付请求成功
                    && depositfacepay.getResultCode().equals(WxPayConstants.ResultCode.SUCCESS)) {//返回结果集成功

                TOrder order = new TOrder();
                //服务商，代理商，商户，门店信息
                order.setBusinessServiceId(serviceId);
                order.setAgentId(agentId);
                order.setProfitSharing("N");
                order.setMerchantId(merchant.getId());
                order.setMerchantName(merchant.getName());
                order.setStoreName(store.getName());
                order.setStoreId(store.getId());
                order.setCode(store.getCode());

                /*消费金额*/
                order.setOrderTotalFee(Long.valueOf(consumeFee) + Long.valueOf(depositFee));
                order.setMemberTotalFee(Long.valueOf(consumeFee) + Long.valueOf(depositFee));
                /*押金金额*/
                order.setDepositFee(Long.valueOf(depositFee));
                order.setPayType(1);
                order.setOutTradeNo(outTradeNo);
                order.setTradeType("DEPOSIT");//人脸支付
                order.setOrderStatus(5);
                order.setTimeEnd(depositfacepay.getTimeEnd());
                //支付信息
                order.setOpenid(depositfacepay.getOpenid());
                order.setTransactionId(depositfacepay.getTransactionId());
                order.setDeviceNo(deviceNo);

                SysUser sysUser = sysUserService.getById(storeUserId);
                if (sysUser != null) {
                    order.setOrderCreateUserName(sysUser.getUsername());
                }
                //店员信息
                order.setStoreUserId(storeUserId);

                order.setSettlementTotalFee(Long.valueOf(depositfacepay.getSettlementTotalFee()));
                order.setRealPayFee(Long.valueOf(depositfacepay.getCashFee()));
                order.setCouponFee(Long.valueOf(depositfacepay.getCouponFee()));

                order.setUpdatedTime(new Date());
                //保存订单信息
                tOrderMapper.insert(order);

                return order;
            } else {
                //用户支付中
                if (depositfacepay.getResultCode().equals(WxPayConstants.ResultCode.FAIL)
                        && depositfacepay.getErrCode().equals("USERPAYING")) {
                    TOrder order = new TOrder();
                    //服务商，代理商，商户，门店信息
                    order.setBusinessServiceId(serviceId);
                    order.setAgentId(agentId);
                    order.setStoreId(store.getId());
                    order.setMerchantName(merchant.getName());
                    order.setMerchantId(merchant.getId());
                    order.setStoreName(store.getName());
                    order.setCode(store.getCode());

                    /*消费金额*/
                    order.setOrderTotalFee(Long.valueOf(consumeFee) + Long.valueOf(depositFee));
                    order.setMemberTotalFee(Long.valueOf(consumeFee) + Long.valueOf(depositFee));
                    /*押金金额*/
                    order.setDepositFee(Long.valueOf(depositFee));
                    order.setOutTradeNo(outTradeNo);
                    order.setPayType(1);
                    order.setTradeType("DEPOSIT");//人脸支付
                    order.setTimeEnd(depositfacepay.getTimeEnd());
                    order.setOrderStatus(0);
                    //支付信息
                    order.setTransactionId(depositfacepay.getTransactionId());
                    order.setDeviceNo(deviceNo);
                    order.setOpenid(depositfacepay.getOpenid());
                    SysUser sysUser = sysUserService.getById(storeUserId);
                    if (sysUser != null) {
                        order.setOrderCreateUserName(sysUser.getUsername());
                    }
                    //店员信息
                    order.setStoreUserId(storeUserId);
                    //保存订单信息
                    tOrderMapper.insert(order);

                    Thread.sleep(3000);
                    return this.queryDepositOrderStatus(order, 1);

                } else {
                    throw new Exception("押金支付失败");
                }
            }
        } catch (WxPayException e) {
            e.printStackTrace();
            throw new Exception(StringUtils.isBlank(e.getErrCodeDes()) ? e.getReturnMsg() : e.getErrCodeDes());
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("押金支付失败");
        }
    }

    @Override
    @Transactional
    public Deposit returndeposit(HttpServletRequest request, String outTradeNo, String deviceNo, Integer consumeFee, Long storeUserId) throws BusinessException, Exception {
        try {
            TOrder torder = tOrderMapper.selectOne(new QueryWrapper<TOrder>().eq("out_trade_no", outTradeNo));
            if (torder == null) {
                throw new BusinessException(9000, "输入订单号不存在！");
            }
            Deposit oldDeposit = depositMapper.selectOne(new QueryWrapper<Deposit>().eq("transaction_id", torder.getTransactionId()));
            if (oldDeposit != null) {
                throw new BusinessException(9001, "已经退押金，不能重复退！");
            }
            Long realConsumeFee;
            Long realFee = torder.getOrderTotalFee();
            if (torder.getSettlementTotalFee() != 0) {
                realFee = torder.getSettlementTotalFee();
            }
            if (consumeFee != null) {
                realConsumeFee = realFee - torder.getDepositFee() + consumeFee;
            } else {
                realConsumeFee = realFee - torder.getDepositFee();
            }
            //获取设备信息
            Device device = deviceService.selectByDeviceNo(deviceNo);
            //获取门店信息
            Store store = storeService.getById(device.getStoreId());
            //获取商户信息
            Merchant merchant = merchantService.getById(store.getMerchantId());

            String merchantCode = merchant.getCode();
            String[] codes = merchantCode.split("-");
            Long agentId = Long.valueOf(codes[1]);//代理商ID
            Long serviceId = Long.valueOf(codes[0]);//服务商ID

            //初始化支付service
            WxPayServiceExt wxPayService = weixinPayService.getServiceExt(merchant.getCode(), merchant.getSubMchId());

            DepositConsumeRequest depositConsumeRequest = new DepositConsumeRequest();
            depositConsumeRequest.setOutTradeNo(outTradeNo);
            depositConsumeRequest.setTransactionId(torder.getTransactionId());
            Integer totalFee = torder.getRealPayFee().intValue();
            depositConsumeRequest.setTotalFee(totalFee);
            depositConsumeRequest.setConsumeFee(Integer.valueOf(realConsumeFee + ""));
            depositConsumeRequest.setFeeType("CNY");
            depositConsumeRequest.setSignType(WxPayConstants.SignType.HMAC_SHA256);

            DepositConsumeResponse depositconsume = wxPayService.depositconsume(depositConsumeRequest);
            if (WxPayConstants.ResultCode.FAIL.equals(depositconsume.getReturnCode())) {
                throw new Exception("押金消费失败");
            }

            if (WxPayConstants.ResultCode.SUCCESS.equals(depositconsume.getReturnCode()) //消费押金请求成功
                    && depositconsume.getResultCode().equals(WxPayConstants.ResultCode.SUCCESS)) {//返回结果集成功

                DepositRefundRequest depositRefundRequest = new DepositRefundRequest();
                depositRefundRequest.setTotalFee(totalFee);
                String outRefundNo = System.currentTimeMillis() + "";
                depositRefundRequest.setOutRefundNo(outRefundNo);
                depositRefundRequest.setTransactionId(torder.getTransactionId());
                depositRefundRequest.setSignType(WxPayConstants.SignType.HMAC_SHA256);
                if (torder.getDepositFee().intValue() == consumeFee.intValue()) {
                    Deposit deposit = new Deposit();
                    //服务商，代理商，商户，门店信息
                    deposit.setBusinessServiceId(serviceId);
                    deposit.setAgentId(agentId);
                    deposit.setMerchantName(merchant.getName());
                    deposit.setMerchantId(merchant.getId());
                    deposit.setStoreId(store.getId());
                    deposit.setStoreName(store.getName());
                    deposit.setCode(store.getCode());

                    /*押金金额*/
                    deposit.setDepositFee(0L);
                    deposit.setDepositStatus(1);
                    deposit.setOpenid(torder.getOpenid());
                    //支付信息
                    deposit.setTransactionId(depositconsume.getTransactionId());
                    deposit.setDeviceNo(deviceNo);
                    deposit.setOutRefundNo(outRefundNo);
                    //店员信息
                    deposit.setStoreUserId(storeUserId);
                    deposit.setDepositStatus(1);
                    this.updateOrderStatus(torder.getId(), realConsumeFee);
                    return deposit;
                }
                /*应退押金金额=总金额-消费金额*/
                Integer depositFee = totalFee - Integer.valueOf(realConsumeFee + "");
                depositRefundRequest.setRefundFee(depositFee);
                DepositRefundResponse depositrefund = wxPayService.depositrefund(depositRefundRequest);
                if (WxPayConstants.ResultCode.FAIL.equals(depositrefund.getReturnCode())) {
                    throw new Exception("押金退回失败");
                }
                if (WxPayConstants.ResultCode.SUCCESS.equals(depositrefund.getReturnCode())) {
                    Deposit deposit = new Deposit();
                    //服务商，代理商，商户，门店信息
                    deposit.setBusinessServiceId(serviceId);
                    deposit.setAgentId(agentId);
                    deposit.setMerchantName(merchant.getName());
                    deposit.setMerchantId(merchant.getId());
                    deposit.setStoreName(store.getName());
                    deposit.setStoreId(store.getId());
                    deposit.setRefundId(depositrefund.getRefundId());
                    deposit.setCode(store.getCode());

                    /*押金金额*/
                    deposit.setDepositFee(Long.valueOf(depositFee));
                    deposit.setDepositStatus(1);
                    deposit.setOpenid(torder.getOpenid());
                    //支付信息
                    deposit.setTransactionId(depositconsume.getTransactionId());
                    deposit.setDeviceNo(deviceNo);
                    deposit.setOutRefundNo(outRefundNo);
                    //店员信息
                    deposit.setStoreUserId(storeUserId);
                    //保存押金信息
                    depositMapper.insert(deposit);
                    this.updateOrderStatus(torder.getId(), realConsumeFee);
                    return deposit;
                } else {
                    Deposit deposit = new Deposit();
                    //服务商，代理商，商户，门店信息
                    deposit.setBusinessServiceId(serviceId);
                    deposit.setAgentId(agentId);
                    deposit.setStoreId(store.getId());
                    deposit.setMerchantName(merchant.getName());
                    deposit.setMerchantId(merchant.getId());
                    deposit.setStoreName(store.getName());
                    deposit.setCode(store.getCode());

                    /*押金金额*/
                    deposit.setDepositFee(Long.valueOf(depositFee));
                    deposit.setDepositStatus(0);
                    //支付信息
                    deposit.setTransactionId(depositconsume.getTransactionId());
                    deposit.setDeviceNo(deviceNo);
                    deposit.setOpenid(torder.getOpenid());
                    deposit.setOutRefundNo(outRefundNo);

                    //店员信息
                    deposit.setStoreUserId(storeUserId);
                    //保存订单信息
                    depositMapper.insert(deposit);

                    Thread.sleep(3000);
                    Deposit deposit1 = queryDepositRefundStatus(deposit, 1);
                    if (deposit1.getDepositStatus() == 1) {
                        this.updateOrderStatus(torder.getId(), realConsumeFee);
                    }
                    return deposit1;
                }
            } else {
                return null;
            }
        } catch (WxPayException e) {
            e.printStackTrace();
            throw new Exception(StringUtils.isBlank(e.getErrCodeDes()) ? e.getReturnMsg() : e.getErrCodeDes());
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("押金支付失败");
        }
    }

    @Override
    public TOrder createTytPayOrder(String faceCode, String deviceNo, Integer totalFee, Integer memberFee, String phone, String outTradeNo, Long storeUserId) throws Exception {
        try {
            //获取设备信息
            Device device = deviceService.selectByDeviceNo(deviceNo);
            //获取门店信息
            Store store = storeService.getById(device.getStoreId());
            //获取商户信息
            Merchant merchant = merchantService.getById(store.getMerchantId());


            String merchantCode = merchant.getCode();
            String[] codes = merchantCode.split("-");
            Long serviceId = Long.valueOf(codes[0]);//服务商ID
            Long agentId = Long.valueOf(codes[1]);//代理商ID

            TytMicropayRequest request = new TytMicropayRequest();
            request.setAccount(merchant.getPayAccount());
            request.setAttach(phone);
            request.setBarcode(faceCode);
            request.setBody(store.getName() + "购买商品刷脸支付");
            request.setLowOrderId(outTradeNo);
            request.setLowCashier(storeUserId + "");
            //支付金额
            Integer payFee = (memberFee != null && memberFee > 0l) ? memberFee : totalFee;
            BigDecimal bg = new BigDecimal(payFee * 0.01);
            DecimalFormat df1 = new DecimalFormat("0.00");
            String fee = df1.format(bg);
            request.setPayMoney(fee);

            request.setPayType("0");
            //设置签名
            String mchKey = merchant.getPayKey();
            request.setSign(MD5Utils.doSign(request, mchKey));

            String url = tytUrl + "/tgPosp/services/payApi/micropay";
            String str = HttpClientUtils.post(url, JSON.toJSONString(request), "UTF-8");
            JSONObject object = JSONObject.parseObject(str);
            TytMicropayResponse response = JSON.toJavaObject(object, TytMicropayResponse.class);
            if (response.getStatus().equals("100")) { //请求成功

                if (response.getState().equals("0")) {
                    TOrder order = new TOrder();
                    //服务商，代理商，商户，门店信息
                    order.setBusinessServiceId(serviceId);
                    order.setAgentId(agentId);
                    order.setMerchantName(merchant.getName());
                    order.setMerchantId(merchant.getId());
                    order.setStoreId(store.getId());
                    order.setStoreName(store.getName());
                    order.setCode(store.getCode());

                    order.setOrderTotalFee(Long.valueOf(totalFee));
                    //会员价格
                    order.setMemberTotalFee(memberFee != null ? Long.valueOf(memberFee) : Long.valueOf(totalFee));
                    order.setCouponFee(0L);
                    order.setSettlementTotalFee((long) (Double.valueOf(response.getPayMoney()) * 100));
                    order.setOutTradeNo(outTradeNo);
                    order.setPayType(4);
                    order.setProfitSharing("N");
                    order.setProfitSharingStatus(0);
                    order.setTradeType("FACEPAY");//人脸支付
                    order.setOrderStatus(1);
                    //支付信息
                    order.setTransactionId(response.getUpOrderId());
                    order.setOpenid(response.getOpenid());
                    order.setDeviceNo(deviceNo);
                    SysUser sysUser = sysUserService.getById(storeUserId);
                    if (sysUser != null) {
                        order.setOrderCreateUserName(sysUser.getUsername());
                    }
                    //店员信息
                    order.setStoreUserId(storeUserId);
                    order.setRealPayFee((long) payFee);
                    order.setTimeEnd(response.getPayTime());

                    if (StringUtils.isNotBlank(response.getAttach())) {//会员电话
                        order.setPhone(response.getAttach());
                    }
                    order.setUpdatedTime(new Date());
                    //保存订单信息
                    tOrderMapper.insert(order);

                    //发送店员收款消息推送
                    storeService.sendWxTempLateReceivables(order);

                    mqSend.sendCheckIsMember(merchant.getId(), null, response.getOpenid(), response.getAttach(), 2, order.getId(), "WXPAY");

                    return order;
                } else if (response.getState().equals(4)) {//待支付
                    TOrder order = new TOrder();
                    //服务商，代理商，商户，门店信息
                    order.setBusinessServiceId(serviceId);
                    order.setAgentId(agentId);
                    order.setMerchantName(merchant.getName());
                    order.setMerchantId(merchant.getId());
                    order.setStoreId(store.getId());
                    order.setStoreName(store.getName());
                    order.setCode(store.getCode());

                    order.setOrderTotalFee(Long.valueOf(totalFee));
                    //会员价格
                    order.setMemberTotalFee(memberFee != null ? Long.valueOf(memberFee) : Long.valueOf(totalFee));
                    order.setOutTradeNo(outTradeNo);
                    order.setPayType(4);
                    order.setProfitSharing("N");
                    order.setProfitSharingStatus(0);
                    order.setTradeType("FACEPAY");//人脸支付
                    order.setOrderStatus(0);
                    //支付信息
                    order.setTransactionId(response.getUpOrderId());
                    order.setOpenid(response.getOpenid());
                    order.setDeviceNo(deviceNo);
                    SysUser sysUser = sysUserService.getById(storeUserId);
                    if (sysUser != null) {
                        order.setOrderCreateUserName(sysUser.getUsername());
                    }
                    //店员信息
                    order.setStoreUserId(storeUserId);
                    order.setRealPayFee((long) payFee);
                    order.setTimeEnd(response.getPayTime());
                    if (StringUtils.isNotBlank(response.getAttach())) {//会员电话
                        order.setPhone(response.getAttach());
                    }
                    //保存订单信息
                    tOrderMapper.insert(order);
                    //1秒后执行支付结果查询
                    Integer times = 1;
                    Thread.sleep(3000);
                    TOrder order1 = queryTytOrderStatus(merchant.getPayAccount(), merchant.getPayKey(), order, times);
                    if (order1.getOrderStatus() == 1) {//支付成功
                        mqSend.sendCheckIsMember(merchant.getId(), null, response.getOpenid(), response.getAttach(), 2, order.getId(), "WXPAY");
                    }
                    return order1;
                } else {
                    throw new Exception("订单支付失败");
                }

            } else {
                log.info("通用通人脸支付返回结果集：" + object);
                throw new Exception(response.getMessage());
            }
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

    @Override
    public String createTytScanPayOrder(String deviceNo, String outTradeNo, Integer totalFee, Integer memberFee, String phone, Long storeUserId) throws Exception {
        //获取设备信息
        Device device = deviceService.selectByDeviceNo(deviceNo);
        //获取门店信息
        Store store = storeService.getById(device.getStoreId());
        //获取商户信息
        Merchant merchant = merchantService.getById(store.getMerchantId());


        TytMicropayRequest request = new TytMicropayRequest();
        request.setAccount(merchant.getPayAccount());
        //支付金额
        Integer payFee = (memberFee != null && memberFee > 0l) ? memberFee : totalFee;
        BigDecimal bg = new BigDecimal(payFee * 0.01);
        DecimalFormat df1 = new DecimalFormat("0.00");
        String fee = df1.format(bg);
        request.setPayMoney(fee);
        request.setLowOrderId(outTradeNo);
        request.setBody(store.getName() + "扫码支付");
        request.setAttach(phone);
        request.setLowCashier(storeUserId + "");

        request.setNotifyUrl(notifyUrl + "/open/tytScanNotify");
        //设置签名
        String mchKey = merchant.getPayKey();
        request.setSign(MD5Utils.doSign(request, mchKey));
        String url = tytUrl + "/tgPosp/services/payApi/allQrcodePay";
        String str = HttpClientUtils.post(url, JSON.toJSONString(request), "UTF-8");
        JSONObject object = JSONObject.parseObject(str);
        TytMicropayResponse response = JSON.toJavaObject(object, TytMicropayResponse.class);
        if (response.getStatus().equals("100")) {
            return response.getCodeUrl();
        } else {
            throw new Exception(response.getMessage());
        }
    }


    @Override
    public Object getCloseAccount(String deviceNo, SysUser sysUser) {
        CloseAccount closeAccount = closeAccountService.selectByFirst(deviceNo);
        TOrder order = new TOrder();
        Date startTime = null;
        if (closeAccount != null) {
            startTime = closeAccount.getCreatedTime();
            order.setBeginTime(startTime);
        }
        order.setDeviceNo(deviceNo);
        order.setStoreUserId(sysUser.getId());
        Date endTime = new Date();
        order.setEndTime(endTime);
        /*查询统计信息*/
        TOrderExt tOrderExt = tOrderMapper.selectCloseAccountStatistics(order);
        tOrderExt.setStoreUserId(sysUser.getId());
        tOrderExt.setStoreUserName(sysUser.getRealName());
        tOrderExt.setBeginTime(startTime != null ? startTime : null);
        tOrderExt.setEndTime(endTime);
        List<TOrder> tOrders = tOrderMapper.selectList(new QueryWrapper<TOrder>().eq("device_no", deviceNo)
                .eq("store_user_id", sysUser.getId()));
        /*保存该数据到统计结算表中*/
        if (tOrderExt != null) {

            CloseAccount account = new CloseAccount();
            if (tOrders != null && tOrders.size() > 0) {
                TOrder tOrder = tOrders.get(0);
                account.setMerchantId(tOrder.getMerchantId());
                account.setMerchantName(tOrder.getMerchantName());
                account.setStoreId(tOrder.getStoreId());
                account.setStoreName(tOrder.getStoreName());
            }

            account.setStoreUserId(sysUser.getId());
            account.setDeviceNo(deviceNo);
            account.setStoreUserName(sysUser.getUsername());
            account.setBeginTime(startTime);
            /*微信结算*/
            JSONObject wxObject = new JSONObject();
            Long wxCount = tOrderExt.getWxCount() == null ? 0 : tOrderExt.getWxCount();
            wxObject.put("wxCount", wxCount);
            String wxFee = tOrderExt.getWxFee() == null ? "0" : tOrderExt.getWxFee();
            wxObject.put("wxFee", wxFee);
            account.setWxDataFee(JSON.toJSONString(wxObject));

            /*支付宝结算*/
            JSONObject aliObject = new JSONObject();
            Long aliCount = tOrderExt.getAliCount() == null ? 0 : tOrderExt.getAliCount();
            aliObject.put("aliCount", aliCount);
            String aliFee = tOrderExt.getAliFee() == null ? "0" : tOrderExt.getAliFee();
            aliObject.put("aliFee", aliFee);
            account.setAliDataFee(JSON.toJSONString(aliObject));

            /*会员余额结算*/
            JSONObject memberObject = new JSONObject();
            Long memberCount = tOrderExt.getMemberCount() == null ? 0 : tOrderExt.getMemberCount();
            memberObject.put("memberCount", memberCount);
            String memberFee = tOrderExt.getMemberFee() == null ? "0" : tOrderExt.getMemberFee();
            memberObject.put("memberFee", memberFee);
            account.setMemberDataFee(JSON.toJSONString(memberObject));

            /*通用通结算*/
            JSONObject tytObject = new JSONObject();
            Long tytCount = tOrderExt.getTytCount() == null ? 0 : tOrderExt.getTytCount();
            tytObject.put("tytCount", tytCount);
            String tytFee = tOrderExt.getTytFee() == null ? "0" : tOrderExt.getTytFee();
            tytObject.put("tytFee", tytFee);
            account.setTytDataFee(JSON.toJSONString(tytObject));

            /*退款数据*/
            JSONObject refundObject = new JSONObject();
            Long refundCount = tOrderExt.getRefundCount() == null ? 0 : tOrderExt.getRefundCount();
            refundObject.put("refundCount", refundCount);
            String refundFee = tOrderExt.getRefundFee() == null ? "0" : tOrderExt.getRefundFee();
            refundObject.put("refundFee", refundFee);
            account.setRefundDataFee(JSON.toJSONString(refundObject));

            /*总结算*/
            JSONObject sumObject = new JSONObject();
            sumObject.put("sumCount", tOrderExt.getSumCount());
            String sumFee = tOrderExt.getSumFee() == null ? "0" : tOrderExt.getSumFee();
            sumObject.put("sumFee", sumFee);
            account.setSumDataFee(JSON.toJSONString(sumObject));

            /*实收*/
            JSONObject settlementObject = new JSONObject();
            String settlementFee = tOrderExt.getSettlementFee() == null ? "0" : tOrderExt.getSettlementFee();
            settlementObject.put("settlementFee", settlementFee);
            account.setSettlementDataFee(JSON.toJSONString(settlementObject));

            /*优惠*/
            JSONObject couponObject = new JSONObject();
            String couponFee = tOrderExt.getCouponTotalFee() == null ? "0" : tOrderExt.getCouponTotalFee();
            couponObject.put("couponTotalFee", couponFee);
            account.setCouponDataFee(JSON.toJSONString(couponObject));

            /*押金*/
            JSONObject depositObject = new JSONObject();
            Long depositCount = tOrderExt.getDepositCount() == null ? 0 : tOrderExt.getDepositCount();
            depositObject.put("depositCount", depositCount);
            String depositFee = tOrderExt.getDepositTotalFee() == null ? "0" : tOrderExt.getDepositTotalFee();
            depositObject.put("depositTotalFee", depositFee);
            account.setDepositDataFee(JSON.toJSONString(depositObject));


            tOrderExt.setSumFee(sumFee);
            tOrderExt.setSettlementFee(settlementFee);
            tOrderExt.setCouponTotalFee(couponFee);
            tOrderExt.setDepositCount(depositCount);
            tOrderExt.setDepositTotalFee(depositFee);
            tOrderExt.setWxCount(wxCount);
            tOrderExt.setWxFee(wxFee);
            tOrderExt.setMemberCount(memberCount);
            tOrderExt.setMemberFee(memberFee);
            tOrderExt.setAliCount(aliCount);
            tOrderExt.setAliFee(aliFee);
            tOrderExt.setTytCount(tytCount);
            tOrderExt.setTytFee(tytFee);
            tOrderExt.setRefundCount(refundCount);
            tOrderExt.setRefundFee(refundFee);

            closeAccountService.save(account);
        }
        //获取设备信息//获取门店信息
        Device device = deviceService.selectByDeviceNo(deviceNo);
        Store store = storeService.getById(device.getStoreId());
        tOrderExt.setStoreName(store.getName());

        return tOrderExt;
    }

    @Override
    public TOrder selectLastByUserIdAndDeviceNo(Long userId, String deviceNo) {
        TOrder order = tOrderMapper.selectLastByUserIdAndDeviceNoXml(userId, deviceNo);
        return order;
    }

    @Override
    public IPage<TOrder> selectListByDeviceNoAndTime(Integer pageNum, Integer pageSize, String deviceNo, String begin, String outTradeNo) throws Exception {

        Date beginTime = null;
        Date endTime = null;
        try {
            if (StringUtils.isNotBlank(begin)) {
                beginTime = DateUtils.paseDatetime(DateUtils.formatDate(DateUtils.parseDate(begin)) + " 00:00:00");
                endTime = DateUtils.paseDatetime(DateUtils.formatDate(beginTime) + " 23:59:59");
            }
        } catch (Exception e) {
            throw new Exception("时间格式转换错误");
        }
        Page<TOrder> page = new Page<>(pageNum, pageSize);
        IPage<TOrder> result = tOrderMapper.selectListByDeviceNoAndTimeXml(page, deviceNo, beginTime, endTime, outTradeNo);
        return result;
    }

    @Override
    public Object selectListByDeviceNoAndTimeAll(String deviceNo, String begin) throws Exception {
        Date beginTime = null;
        Date endTime = null;
        Map map = new HashMap();
        try {
            if (StringUtils.isNotBlank(begin)) {
                beginTime = DateUtils.paseDatetime(DateUtils.formatDate(DateUtils.parseDate(begin)) + " 00:00:00");
                endTime = DateUtils.paseDatetime(DateUtils.formatDate(beginTime) + " 23:59:59");
            }
            List<TOrder> result = tOrderMapper.selectListByDeviceNoAndTimeXml(deviceNo, beginTime, endTime, null);
            map.put("beginTime", DateUtils.formatDatetime(beginTime));
            map.put("endTime", DateUtils.formatDatetime(endTime));
            map.put("list", result);
        } catch (Exception e) {
            throw new Exception("时间格式转换错误");
        }
        return map;
    }

    @Override
    public Object getCloseAccountPrint(String deviceNo, String begin,SysUser user) throws Exception {
        Date beginTime = null;
        Date endTime = null;
        try {
            if (StringUtils.isNotBlank(begin)) {
                beginTime = DateUtils.paseDatetime(DateUtils.formatDate(DateUtils.parseDate(begin)) + " 00:00:00");
                ;
                endTime = DateUtils.paseDatetime(DateUtils.formatDate(beginTime) + " 23:59:59");
            }
        } catch (Exception e) {
            throw new Exception("时间格式转换错误");
        }
        TOrder order = new TOrder();
        order.setBeginTime(beginTime);
        order.setDeviceNo(deviceNo);
        order.setEndTime(endTime);
        /*查询统计信息*/
        TOrderExt tOrderExt = tOrderMapper.selectCloseAccountStatistics(order);
        tOrderExt.setBeginTime(beginTime);
        tOrderExt.setEndTime(endTime);
        if (tOrderExt != null) {
            Long wxCount = tOrderExt.getWxCount() == null ? 0 : tOrderExt.getWxCount();
            String wxFee = tOrderExt.getWxFee() == null ? "0" : tOrderExt.getWxFee();
            Long aliCount = tOrderExt.getAliCount() == null ? 0 : tOrderExt.getAliCount();
            String aliFee = tOrderExt.getAliFee() == null ? "0" : tOrderExt.getAliFee();
            Long memberCount = tOrderExt.getMemberCount() == null ? 0 : tOrderExt.getMemberCount();
            String memberFee = tOrderExt.getMemberFee() == null ? "0" : tOrderExt.getMemberFee();
            Long tytCount = tOrderExt.getTytCount() == null ? 0 : tOrderExt.getTytCount();
            String tytFee = tOrderExt.getTytFee() == null ? "0" : tOrderExt.getTytFee();
            Long refundCount = tOrderExt.getRefundCount() == null ? 0 : tOrderExt.getRefundCount();
            String refundFee = tOrderExt.getRefundFee() == null ? "0" : tOrderExt.getRefundFee();
            String sumFee = tOrderExt.getSumFee() == null ? "0" : tOrderExt.getSumFee();
            String settlementFee = tOrderExt.getSettlementFee() == null ? "0" : tOrderExt.getSettlementFee();
            String couponTotalFee = tOrderExt.getCouponTotalFee() == null ? "0" : tOrderExt.getCouponTotalFee();
            Long depositCount = tOrderExt.getDepositCount() == null ? 0 : tOrderExt.getDepositCount();
            String depositTotalFee = tOrderExt.getDepositTotalFee() == null ? "0" : tOrderExt.getDepositTotalFee();


            tOrderExt.setSumFee(sumFee);
            tOrderExt.setSettlementFee(settlementFee);
            tOrderExt.setCouponTotalFee(couponTotalFee);
            tOrderExt.setDepositCount(depositCount);
            tOrderExt.setDepositTotalFee(depositTotalFee);
            tOrderExt.setWxCount(wxCount);
            tOrderExt.setWxFee(wxFee);
            tOrderExt.setMemberCount(memberCount);
            tOrderExt.setMemberFee(memberFee);
            tOrderExt.setAliCount(aliCount);
            tOrderExt.setAliFee(aliFee);
            tOrderExt.setTytCount(tytCount);
            tOrderExt.setTytFee(tytFee);
            tOrderExt.setRefundCount(refundCount);
            tOrderExt.setRefundFee(refundFee);
        }
        //获取设备信息//获取门店信息
        Device device = deviceService.selectByDeviceNo(deviceNo);
        Store store = storeService.getById(device.getStoreId());
        tOrderExt.setStoreName(store.getName());
        tOrderExt.setStoreUserName(user.getRealName());
        return tOrderExt;
    }

    @Override
    public boolean tytRefund(TOrder tOrder, Merchant merchant, SysUser user) throws Exception {

        TytMicropayRequest request = new TytMicropayRequest();
        request.setAccount(merchant.getPayAccount());
        request.setUpOrderId(tOrder.getTransactionId());
        Device device = deviceService.selectByDeviceNo(tOrder.getDeviceNo());
        String outRefundNo = device.getId() + System.currentTimeMillis() + ApplicationUtils.getRandomStr(5);
        request.setLowOrderId(tOrder.getOutTradeNo());
        //设置签名
        String mchKey = merchant.getPayKey();
        request.setSign(MD5Utils.doSign(request, mchKey));
        String url = tytUrl + "/tgPosp/services/payApi/reverse";
        String str = HttpClientUtils.post(url, JSON.toJSONString(request), "UTF-8");
        JSONObject object = JSONObject.parseObject(str);
        if (object.getInteger("status") == 100) {
            if (object.getInteger("state") == 2 || object.getInteger("state") == 5) {//已经发起退款

                TOrder order = new TOrder();
                order.setId(tOrder.getId());
                order.setOrderStatus(3);
                order.setRefundUserId(user.getId());
                order.setOrderRefundUserName(user.getUsername());
                tOrderMapper.updateById(order);

                RefundRecord refundRecord = new RefundRecord();
                refundRecord.setOutTradeNo(tOrder.getOutTradeNo());
                refundRecord.setOutRefundNo(outRefundNo);
                refundRecord.setPayType(4);
                refundRecord.setStatus(1);
                refundRecord.setTransactionId(tOrder.getTransactionId());
                refundRecord.setStoreId(tOrder.getStoreId());
                refundRecord.setUserId(tOrder.getOpenid());
                refundRecordService.save(refundRecord);

                return true;
            } else {
                throw new Exception("退款失败");
            }
        } else {
            throw new Exception(object.getString("message"));
        }
    }

    @Override
    public boolean memberRefund(TOrder tOrder, Merchant merchant, SysUser user) {
        Member member = memberService.selectByMerchantIdAndMobileAndStatus(tOrder.getMerchantId(), tOrder.getPhone(), 1);
        if (member == null) {
            return false;
        }

        TOrder order = new TOrder();
        order.setId(tOrder.getId());
        order.setOrderStatus(3);
        order.setRefundUserId(user.getId());
        order.setOrderRefundUserName(user.getUsername());
        tOrderMapper.updateById(order);
        String outRefundNo = System.currentTimeMillis() + "";


        RefundRecord refundRecord = new RefundRecord();
        refundRecord.setOutTradeNo(tOrder.getOutTradeNo());
        refundRecord.setPayType(1);
        refundRecord.setStatus(1);
        refundRecord.setTransactionId(tOrder.getTransactionId());
        refundRecord.setOutRefundNo(outRefundNo);
        refundRecord.setRefundFee(tOrder.getMemberTotalFee());
        refundRecord.setStoreId(tOrder.getStoreId());
        refundRecord.setUserId(tOrder.getOpenid());
        refundRecordService.save(refundRecord);

        //修改会员余额
        member.setTotalBalances(member.getTotalBalances() + tOrder.getMemberTotalFee());

        //计算获得的积分
        Long payTotal = (tOrder.getMemberTotalFee() == null || tOrder.getMemberTotalFee() == 0 ? tOrder.getOrderTotalFee() : tOrder.getMemberTotalFee());
        Long integral = (payTotal / merchant.getMonetary());
        member.setTotalIntegral((member.getTotalIntegral() - integral) < 0 ? 0l : (member.getTotalIntegral() - integral));
        memberService.saveOrUpdate(member);

        return true;
    }

    @Override
    public Map apiStatisticsByMerchant(Long merchandId, String queryTime, Integer quertType, Integer orderType) {
        Date beginTime = null;
        Date endTime = null;
        if (quertType == 0) {
            Date fmtDate = DateUtils.parseDate(queryTime, "yyyy-MM-dd");
            beginTime = DateUtils.getDateBegin(fmtDate);
            endTime = DateUtils.getDateEnd(beginTime);
        } else if (quertType == 1) {
            Date fmtDate = DateUtils.parseDate(queryTime, "yyyy-MM");
            beginTime = DateUtils.getMonthBegin(fmtDate);
            endTime = DateUtils.getMonthEnd(beginTime);
        } else {
            Date fmtDate = DateUtils.parseDate(queryTime, "yyyy");
            beginTime = DateUtils.getYearBegin(fmtDate);
            endTime = DateUtils.getYearEnd(beginTime);
        }

        Merchant merchant = merchantService.getById(merchandId);
        TOrder params = new TOrder();
        if (orderType != 0) {
            params.setPayType(orderType);
        }
        params.setBeginTime(beginTime);
        params.setEndTime(endTime);
        Map map = tOrderMapper.selectListStatisticsXml(params, merchant.getCode());

        if (map != null) {
            map.put("sumCount", map.get("sumCount") == null ? 0 : map.get("sumCount"));
            map.put("sumFee", map.get("sumFee") == null ? 0 : map.get("sumFee"));
            map.put("settlementFee", map.get("settlementFee") == null ? 0 : map.get("settlementFee"));
            map.put("couponTotalFee", map.get("couponTotalFee") == null ? 0 : map.get("couponTotalFee"));
            map.put("refundCount", map.get("refundCount") == null ? 0 : map.get("refundCount"));
            map.put("refundFee", map.get("refundFee") == null ? 0 : map.get("refundFee"));
            map.put("wxCount", map.get("wxCount") == null ? 0 : map.get("wxCount"));
            map.put("wxFee", map.get("wxFee") == null ? 0 : map.get("wxFee"));
            map.put("aliCount", map.get("aliCount") == null ? 0 : map.get("aliCount"));
            map.put("aliFee", map.get("aliFee") == null ? 0 : map.get("aliFee"));
            map.put("memberCount", map.get("memberCount") == null ? 0 : map.get("memberCount"));
            map.put("memberFee", map.get("memberFee") == null ? 0 : map.get("memberFee"));
            map.put("tytCount", map.get("tytCount") == null ? 0 : map.get("tytCount"));
            map.put("tytFee", map.get("tytFee") == null ? 0 : map.get("tytFee"));
            map.put("depositCount", map.get("depositCount") == null ? 0 : map.get("depositCount"));
            map.put("depositTotalFee", map.get("couponTotalFee") == null ? 0 : map.get("couponTotalFee"));
        }
        return map;
    }

    @Override
    public IPage<Map> apiStatisticsListByMerchant(Integer pageNum, Integer pageSize, Long merchandId, String queryTime, Integer quertType, Integer orderType) {
        Date beginTime = null;
        Date endTime = null;
        if (quertType == 0) {
            Date fmtDate = DateUtils.parseDate(queryTime, "yyyy-MM-dd");
            beginTime = DateUtils.getDateBegin(fmtDate);
            endTime = DateUtils.getDateEnd(beginTime);
        } else if (quertType == 1) {
            Date fmtDate = DateUtils.parseDate(queryTime, "yyyy-MM");
            beginTime = DateUtils.getMonthBegin(fmtDate);
            endTime = DateUtils.getMonthEnd(beginTime);
        } else {
            Date fmtDate = DateUtils.parseDate(queryTime, "yyyy");
            beginTime = DateUtils.getYearBegin(fmtDate);
            endTime = DateUtils.getYearEnd(beginTime);
        }

        TOrder params = new TOrder();
        if (orderType != 0) {
            params.setPayType(orderType);
        }
        params.setBeginTime(beginTime);
        params.setEndTime(endTime);
        params.setMerchantId(merchandId);

        Page<Map> page = new Page<>(pageNum, pageSize);
        IPage<Map> result = tOrderMapper.selectStatisticsListByMerchant(page, params);
        return result;
    }

    @Override
    public Map apiStatisticsByStore(Long storeId, Long storeUserId, String queryTime, Integer quertType, Integer orderType) {
        Date beginTime = null;
        Date endTime = null;
        if (quertType == 0) {
            Date fmtDate = DateUtils.parseDate(queryTime, "yyyy-MM-dd");
            beginTime = DateUtils.getDateBegin(fmtDate);
            endTime = DateUtils.getDateEnd(beginTime);
        } else if (quertType == 1) {
            Date fmtDate = DateUtils.parseDate(queryTime, "yyyy-MM");
            beginTime = DateUtils.getMonthBegin(fmtDate);
            endTime = DateUtils.getMonthEnd(beginTime);
        } else {
            Date fmtDate = DateUtils.parseDate(queryTime, "yyyy");
            beginTime = DateUtils.getYearBegin(fmtDate);
            endTime = DateUtils.getYearEnd(beginTime);
        }

        Store store = storeService.getById(storeId);
        TOrder params = new TOrder();
        if (orderType != 0) {
            params.setPayType(orderType);
        }
        params.setBeginTime(beginTime);
        params.setEndTime(endTime);
        params.setStoreUserId(storeUserId);
        Map map = tOrderMapper.selectListStatisticsXml(params, store.getCode());
        if (map != null) {
            map.put("sumCount", map.get("sumCount") == null ? 0 : map.get("sumCount"));
            map.put("sumFee", map.get("sumFee") == null ? 0 : map.get("sumFee"));
            map.put("settlementFee", map.get("settlementFee") == null ? 0 : map.get("settlementFee"));
            map.put("couponTotalFee", map.get("couponTotalFee") == null ? 0 : map.get("couponTotalFee"));
            map.put("refundCount", map.get("refundCount") == null ? 0 : map.get("refundCount"));
            map.put("refundFee", map.get("refundFee") == null ? 0 : map.get("refundFee"));
            map.put("wxCount", map.get("wxCount") == null ? 0 : map.get("wxCount"));
            map.put("wxFee", map.get("wxFee") == null ? 0 : map.get("wxFee"));
            map.put("aliCount", map.get("aliCount") == null ? 0 : map.get("aliCount"));
            map.put("aliFee", map.get("aliFee") == null ? 0 : map.get("aliFee"));
            map.put("memberCount", map.get("memberCount") == null ? 0 : map.get("memberCount"));
            map.put("memberFee", map.get("memberFee") == null ? 0 : map.get("memberFee"));
            map.put("tytCount", map.get("tytCount") == null ? 0 : map.get("tytCount"));
            map.put("tytFee", map.get("tytFee") == null ? 0 : map.get("tytFee"));
            map.put("depositCount", map.get("depositCount") == null ? 0 : map.get("depositCount"));
            map.put("depositTotalFee", map.get("couponTotalFee") == null ? 0 : map.get("couponTotalFee"));
        }
        return map;
    }

    @Override
    public IPage<Map> apiStatisticsListByStore(Long storeId, Long storeUserId, Integer pageNum, Integer pageSize, String queryTime, Integer quertType, Integer orderType) {
        Date beginTime = null;
        Date endTime = null;
        if (quertType == 0) {
            Date fmtDate = DateUtils.parseDate(queryTime, "yyyy-MM-dd");
            beginTime = DateUtils.getDateBegin(fmtDate);
            endTime = DateUtils.getDateEnd(beginTime);
        } else if (quertType == 1) {
            Date fmtDate = DateUtils.parseDate(queryTime, "yyyy-MM");
            beginTime = DateUtils.getMonthBegin(fmtDate);
            endTime = DateUtils.getMonthEnd(beginTime);
        } else {
            Date fmtDate = DateUtils.parseDate(queryTime, "yyyy");
            beginTime = DateUtils.getYearBegin(fmtDate);
            endTime = DateUtils.getYearEnd(beginTime);
        }

        TOrder params = new TOrder();
        if (orderType != 0) {
            params.setPayType(orderType);
        }
        params.setBeginTime(beginTime);
        params.setEndTime(endTime);
        params.setStoreId(storeId);
        params.setStoreUserId(storeUserId);
        Page<Map> page = new Page<>(pageNum, pageSize);
        IPage<Map> result = tOrderMapper.selectStatisticsListByStore(page, params);
        return result;
    }

    @Override
    @Transactional
    public TOrder aliBarCodePay(String authCode, String deviceNo, Integer totalFee, Integer memberFee, String outTradeNo, Long userId) throws AlipayApiException, Exception {
        AlipayTradePayRequest request = new AlipayTradePayRequest();
        //获取设备信息
        Device device = deviceService.selectByDeviceNo(deviceNo);
        //获取门店信息
        Store store = storeService.getById(device.getStoreId());
        //获取商户信息
        Merchant merchant = merchantService.getById(store.getMerchantId());
        //获取服务商信息
        ServiceBusiness business = serviceBusinessService.getById(device.getBusinessServiceId());

        //初始化支付宝SDK客户端
        CertAlipayRequest certAlipayRequest = AliClientUtil.initCertAlipayRequest(
                business.getAliAppId(), business.getAliPrivateKey(), business.getAppCertPublicKey(), business.getAlipayCertPublicKey(), business.getAlipayRootCert());
        AlipayClient client = new DefaultAlipayClient(certAlipayRequest);
        if (StringUtils.isBlank(outTradeNo)) {
            outTradeNo = tradeNoService.getTradeNo();
            //outTradeNo = device.getId() + System.currentTimeMillis() + ApplicationUtils.getRandomStr(5);
        }
        AlipayTradePayModel model = new AlipayTradePayModel();
        model.setOutTradeNo(outTradeNo);
        model.setScene("bar_code");
        Double dFee = (memberFee != null && memberFee > 0) ? (memberFee * 0.01) : (totalFee * 0.01);
        BigDecimal bg = new BigDecimal(dFee);
        DecimalFormat df1 = new DecimalFormat("0.00");
        String fee = df1.format(bg);
        model.setSubject("缴费");
        model.setTotalAmount(fee);
        model.setAuthCode(authCode);
        model.setTerminalId(deviceNo);
        /*ExtendParams extendParams = new ExtendParams();
        extendParams.setSysServiceProviderId(business.getProviderId());
        model.setExtendParams(extendParams);*/
        //回调地址
        request.setBizModel(model);
        request.putOtherTextParam("app_auth_token", merchant.getAliAuthToken());
        AlipayTradePayResponse alipayTradePayResponse = client.certificateExecute(request);

        TOrder order = new TOrder();
        //服务商，代理商，商户，门店信息
        order.setBusinessServiceId(business.getId());
        order.setAgentId(merchant.getAgentId());
        order.setProfitSharing("N");
        order.setMerchantId(merchant.getId());
        order.setMerchantName(merchant.getName());
        order.setStoreName(store.getName());
        order.setStoreId(store.getId());
        order.setCode(store.getCode());
        order.setPayType(2);
        order.setOutTradeNo(outTradeNo);
        order.setTradeType("SCAN");//人脸支付
        order.setOrderStatus(0);
        order.setDeviceNo(deviceNo);
        BigDecimal bigDecimal = new BigDecimal("100");
        //会员价格
        order.setMemberTotalFee(memberFee != null ? Long.valueOf(memberFee) : Long.valueOf(totalFee));
        /*消费金额*/
        order.setOrderTotalFee(Long.valueOf(totalFee));
        /*支付成功*/
        if ("10000".equals(alipayTradePayResponse.getCode())) {
            order.setTransactionId(alipayTradePayResponse.getTradeNo());

            order.setTimeEnd(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(alipayTradePayResponse.getGmtPayment()));
            //支付信息
            order.setOpenid(alipayTradePayResponse.getBuyerUserId());

            SysUser sysUser = sysUserService.getById(userId);
            if (sysUser != null) {
                order.setOrderCreateUserName(sysUser.getUsername());
            }
            //店员信息
            order.setStoreUserId(userId);

            //order.setSettlementTotalFee(Long.valueOf(alipayTradePayResponse.getSettleAmount()));
            BigDecimal receiptFee = bigDecimal.multiply(new BigDecimal(alipayTradePayResponse.getReceiptAmount()));
            order.setRealPayFee(receiptFee.longValue());
            if (alipayTradePayResponse.getMdiscountAmount() != null) {
                BigDecimal multiply = bigDecimal.multiply(new BigDecimal(alipayTradePayResponse.getMdiscountAmount()));
                order.setCouponFee(multiply.longValue());
            }
            order.setUpdatedTime(new Date());
            //保存订单信息
            tOrderMapper.insert(order);
        } else if ("10003".equals(alipayTradePayResponse.getCode())) {
            tOrderMapper.insert(order);
            this.queryAliOrderStatus(order, 3, client);
        } else {
            return null;
        }
        return order;
    }

    @Override
    public Map apiStatisticsByStoreUser(Long storeUserId, String queryTime, Integer quertType, Integer orderType) {
        Date beginTime = null;
        Date endTime = null;
        if (quertType == 0) {
            Date fmtDate = DateUtils.parseDate(queryTime, "yyyy-MM-dd");
            beginTime = DateUtils.getDateBegin(fmtDate);
            endTime = DateUtils.getDateEnd(beginTime);
        } else if (quertType == 1) {
            Date fmtDate = DateUtils.parseDate(queryTime, "yyyy-MM");
            beginTime = DateUtils.getMonthBegin(fmtDate);
            endTime = DateUtils.getMonthEnd(beginTime);
        } else {
            Date fmtDate = DateUtils.parseDate(queryTime, "yyyy");
            beginTime = DateUtils.getYearBegin(fmtDate);
            endTime = DateUtils.getYearEnd(beginTime);
        }

        SysUser storeUser = sysUserService.getById(storeUserId);
        TOrder params = new TOrder();
        if (orderType != 0) {
            params.setPayType(orderType);
        }
        params.setBeginTime(beginTime);
        params.setEndTime(endTime);
        params.setStoreUserId(storeUserId);
        params.setStoreId(storeUser.getParentId());
        Map map = tOrderMapper.selectListStatisticsXml(params, null);
        if (map != null) {
            map.put("sumCount", map.get("sumCount") == null ? 0 : map.get("sumCount"));
            map.put("sumFee", map.get("sumFee") == null ? 0 : map.get("sumFee"));
            map.put("settlementFee", map.get("settlementFee") == null ? 0 : map.get("settlementFee"));
            map.put("couponTotalFee", map.get("couponTotalFee") == null ? 0 : map.get("couponTotalFee"));
            map.put("refundCount", map.get("refundCount") == null ? 0 : map.get("refundCount"));
            map.put("refundFee", map.get("refundFee") == null ? 0 : map.get("refundFee"));
            map.put("wxCount", map.get("wxCount") == null ? 0 : map.get("wxCount"));
            map.put("wxFee", map.get("wxFee") == null ? 0 : map.get("wxFee"));
            map.put("aliCount", map.get("aliCount") == null ? 0 : map.get("aliCount"));
            map.put("aliFee", map.get("aliFee") == null ? 0 : map.get("aliFee"));
            map.put("memberCount", map.get("memberCount") == null ? 0 : map.get("memberCount"));
            map.put("memberFee", map.get("memberFee") == null ? 0 : map.get("memberFee"));
            map.put("tytCount", map.get("tytCount") == null ? 0 : map.get("tytCount"));
            map.put("tytFee", map.get("tytFee") == null ? 0 : map.get("tytFee"));
            map.put("depositCount", map.get("depositCount") == null ? 0 : map.get("depositCount"));
            map.put("depositTotalFee", map.get("couponTotalFee") == null ? 0 : map.get("couponTotalFee"));
        }
        return map;
    }

    @Override
    public IPage<TOrder> apiStatisticsListByStoreUser(Long storeUserId, Integer pageNum, Integer pageSize, String queryTime, Integer quertType, Integer orderType) {
        Date beginTime = null;
        Date endTime = null;
        if (quertType == 0) {
            Date fmtDate = DateUtils.parseDate(queryTime, "yyyy-MM-dd");
            beginTime = DateUtils.getDateBegin(fmtDate);
            endTime = DateUtils.getDateEnd(beginTime);
        } else if (quertType == 1) {
            Date fmtDate = DateUtils.parseDate(queryTime, "yyyy-MM");
            beginTime = DateUtils.getMonthBegin(fmtDate);
            endTime = DateUtils.getMonthEnd(beginTime);
        } else {
            Date fmtDate = DateUtils.parseDate(queryTime, "yyyy");
            beginTime = DateUtils.getYearBegin(fmtDate);
            endTime = DateUtils.getYearEnd(beginTime);
        }
        SysUser storeUser = sysUserService.getById(storeUserId);
        TOrder params = new TOrder();
        if (orderType != 0) {
            params.setPayType(orderType);
        }
        params.setBeginTime(beginTime);
        params.setEndTime(endTime);
        params.setStoreUserId(storeUserId);
        params.setStoreId(storeUser.getParentId());
        Page<TOrder> page = new Page<>(pageNum, pageSize);
        IPage<TOrder> result = tOrderMapper.selectListXml(page, params, null);
        return result;
    }


    public TOrder queryAliOrderStatus(TOrder order, Integer times, AlipayClient client) throws Exception {
        try {
            //获取实时最新订单
            Merchant merchant = merchantService.getById(order.getMerchantId());
            //查询订单
            AlipayTradeQueryRequest queryRequest = new AlipayTradeQueryRequest();
            AlipayTradePayModel model = new AlipayTradePayModel();
            model.setOutTradeNo(order.getOutTradeNo());
            //回调地址
            queryRequest.setBizModel(model);
            queryRequest.putOtherTextParam("app_auth_token", merchant.getAliAuthToken());
            AlipayTradeQueryResponse alipayTradeQueryResponse = client.certificateExecute(queryRequest);
            //处理订单查询结果
            if ("10000".equals(alipayTradeQueryResponse.getCode()) && "TRADE_SUCCESS".equals(alipayTradeQueryResponse.getTradeStatus())) {//查询结果成功
                order.setTimeEnd(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(alipayTradeQueryResponse.getSendPayDate()));
                //支付成功
                order.setOrderStatus(1);
                BigDecimal bigDecimal = new BigDecimal(100);
                order.setSettlementTotalFee(Long.valueOf(alipayTradeQueryResponse.getSettleAmount()));
                BigDecimal receiptFee = bigDecimal.multiply(new BigDecimal(alipayTradeQueryResponse.getTotalAmount()));
                order.setRealPayFee(receiptFee.longValue());
                if (alipayTradeQueryResponse.getMdiscountAmount() != null) {
                    BigDecimal multiply = bigDecimal.multiply(new BigDecimal(alipayTradeQueryResponse.getMdiscountAmount()));
                    order.setCouponFee(multiply.longValue());
                }
                order.setTransactionId(alipayTradeQueryResponse.getTradeNo());
                //修改订单状态
                tOrderMapper.updateById(order);
            } else {
                //交易失败
                if ("10003".equals(alipayTradeQueryResponse.getCode())) {

                    if (times <= 10) {
                        times++;
                        //二次查询，再次等待
                        Thread.sleep(3000);
                        this.queryAliOrderStatus(order, times, client);
                    }
                }
                //交易失败
                if ("40004".equals(alipayTradeQueryResponse.getCode())) {
                    //支付失败
                    order.setOrderStatus(2);
                    //修改订单状态
                    tOrderMapper.updateById(order);
                }
            }
        } catch (AlipayApiException e) {
            throw new Exception(e.getErrCode());
        } catch (Exception e) {
            throw new Exception("查询订单状态失败");
        }
        return order;
    }


    @Override
    public boolean refund(TOrder tOrder, Merchant merchant, SysUser user) throws WxPayException {
        WxPayService wxPayService = weixinPayService.getServiceExt(tOrder.getCode(), merchant.getSubMchId());
        WxPayConfig payConfig = wxPayService.getConfig();
        wxPayService.setConfig(payConfig);
        WxPayRefundRequest request = new WxPayRefundRequest();
        request.setOutTradeNo(tOrder.getOutTradeNo());
        String outRefundNo = System.currentTimeMillis() + "";
        request.setOutRefundNo(outRefundNo);
        request.setTotalFee(Integer.valueOf(tOrder.getOrderTotalFee() + ""));
        request.setRefundFee(Integer.valueOf(tOrder.getRealPayFee() + ""));
        WxPayRefundResult refund = wxPayService.refund(request);
        if ("SUCCESS".equalsIgnoreCase(refund.getReturnCode())) {
            if ("SUCCESS".equalsIgnoreCase(refund.getResultCode())) {
                /*查询订单是否退款成功*/
                WxPayConfig payConfigQuery = wxPayService.getConfig();
                wxPayService.setConfig(payConfigQuery);
                payConfig.setSubMchId(merchant.getSubMchId());
                WxPayRefundQueryResult refundQuery = wxPayService.refundQuery(tOrder.getTransactionId(), "", "", "");
                if ("SUCCESS".equalsIgnoreCase(refundQuery.getReturnCode())) {
                    if ("SUCCESS".equalsIgnoreCase(refundQuery.getResultCode())) {

                        TOrder order = new TOrder();
                        order.setId(tOrder.getId());
                        order.setOrderStatus(3);
                        order.setRefundUserId(user.getId());
                        order.setOrderRefundUserName(user.getUsername());
                        tOrderMapper.updateById(order);

                        RefundRecord refundRecord = new RefundRecord();
                        refundRecord.setOutTradeNo(tOrder.getOutTradeNo());
                        refundRecord.setPayType(1);
                        refundRecord.setStatus(1);
                        refundRecord.setTransactionId(tOrder.getTransactionId());
                        refundRecord.setOutRefundNo(refund.getOutRefundNo());
                        refundRecord.setRefundFee(Long.valueOf(refund.getRefundFee()));
                        refundRecord.setStoreId(tOrder.getStoreId());
                        refundRecord.setUserId(tOrder.getOpenid());
                        refundRecordService.save(refundRecord);

                        return true;
                    }
                }
                return false;
            }
        }
        return false;
    }

    @Override
    public boolean refundQuery(TOrder tOrder, Merchant merchant) throws WxPayException {
        WxPayService wxPayService = weixinPayService.getServiceExt(tOrder.getCode(), merchant.getSubMchId());
        WxPayConfig payConfig = wxPayService.getConfig();
        wxPayService.setConfig(payConfig);
        payConfig.setSubMchId(merchant.getSubMchId());
        WxPayRefundQueryResult refundQuery = wxPayService.refundQuery(tOrder.getTransactionId(), "", "", "");
        if ("SUCCESS".equalsIgnoreCase(refundQuery.getReturnCode())) {
            if ("SUCCESS".equalsIgnoreCase(refundQuery.getResultCode())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean aliRefund(TOrder tOrder, Merchant merchant, SysUser user) throws AlipayApiException {
        //获取服务商信息
        ServiceBusiness business = serviceBusinessService.getById(tOrder.getBusinessServiceId());

        CertAlipayRequest certAlipayRequest = AliClientUtil.initCertAlipayRequest(
                business.getAliAppId(), business.getAliPrivateKey(), business.getAppCertPublicKey(), business.getAlipayCertPublicKey(), business.getAlipayRootCert());

        AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        Long realPayFee = tOrder.getRealPayFee();
        Double dFee = (realPayFee != null && realPayFee > 0) ? (realPayFee * 0.01) : (realPayFee * 0.01);
        BigDecimal bg = new BigDecimal(dFee);
        DecimalFormat df1 = new DecimalFormat("0.00");
        String fee = df1.format(bg);
        AlipayTradeRefundModel alipayObject = new AlipayTradeRefundModel();

        alipayObject.setRefundAmount(fee);
        alipayObject.setOutTradeNo(tOrder.getOutTradeNo());
        request.setBizModel(alipayObject);
        request.putOtherTextParam("app_auth_token", merchant.getAliAuthToken());
        AlipayTradeRefundResponse refundResponse = alipayClient.certificateExecute(request);
        /*支付宝退款结果通知*/
        if (refundResponse.isSuccess()) {
            /*退款成功，查询订单是否退款执行成功*/
            AlipayTradeFastpayRefundQueryRequest queryRequest = new AlipayTradeFastpayRefundQueryRequest();
            AlipayTradeRefundApplyModel queryModel = new AlipayTradeRefundApplyModel();
            queryModel.setOutRequestNo(tOrder.getOutTradeNo());
            queryModel.setOutTradeNo(tOrder.getOutTradeNo());
            queryRequest.setBizModel(queryModel);
            queryRequest.putOtherTextParam("app_auth_token", merchant.getAliAuthToken());
            AlipayTradeFastpayRefundQueryResponse refundQueryResponse = alipayClient.certificateExecute(queryRequest);
            if (refundQueryResponse.isSuccess()) {

                TOrder order = new TOrder();
                order.setId(tOrder.getId());
                order.setOrderStatus(3);
                order.setRefundUserId(user.getId());
                order.setOrderRefundUserName(user.getUsername());
                tOrderMapper.updateById(order);

                RefundRecord refundRecord = new RefundRecord();
                refundRecord.setOutTradeNo(tOrder.getOutTradeNo());
                refundRecord.setPayType(2);
                refundRecord.setStatus(1);
                refundRecord.setTransactionId(tOrder.getTransactionId());
                refundRecord.setOutRefundNo(refundResponse.getTradeNo());
                /*费用都要乘100，数据库用分计算*/
                BigDecimal refundFee = new BigDecimal(refundResponse.getRefundFee()).multiply(new BigDecimal(100));
                refundRecord.setRefundFee(refundFee.longValue());
                refundRecord.setStoreId(tOrder.getStoreId());
                refundRecord.setUserId(refundResponse.getOpenId());
                refundRecordService.save(refundRecord);

                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 执行通用通订单查询
     *
     * @param payAccount 账号
     * @param payKey     密匙
     * @param order      订单信息
     * @param times      是否执行下一次查询
     */
    private TOrder queryTytOrderStatus(String payAccount, String payKey, TOrder order, Integer times) throws Exception {
        TytOrderQueryRequest request = new TytOrderQueryRequest();
        request.setAccount(payAccount);
        request.setLowOrderId(order.getOutTradeNo());
        request.setUpOrderId(order.getTransactionId());
        request.setSign(MD5Utils.doSign(request, payKey));
        String url = tytUrl + "/tgPosp/services/payApi/orderQuery";
        String str = HttpClientUtils.post(url, JSON.toJSONString(request), "UTF-8");
        JSONObject object = JSONObject.parseObject(str);
        TytMicropayResponse response = JSON.toJavaObject(object, TytMicropayResponse.class);
        if (response.getStatus().equals("100")) {
            if (response.getState().equals("1")) {//支付成功
                order.setOrderStatus(1);
                order.setOpenid(response.getOpenid());
                order.setCouponFee(0L);
                order.setSettlementTotalFee((long) (Double.valueOf(response.getPayMoney()) * 100));
                tOrderMapper.updateById(order);

                //发送店员收款消息推送
                storeService.sendWxTempLateReceivables(order);

            } else if (response.getState().equals("4")) {//待支付
                if (times < 10) {//是否继续查询
                    //10秒后再次执行查询
                    times++;
                    Thread.sleep(3000);
                    queryTytOrderStatus(payAccount, payKey, order, times);
                } else {
                    order.setOrderStatus(2);
                    tOrderMapper.updateById(order);
                    throw new Exception("订单支付失败");
                }
            } else {
                throw new Exception(response.getMessage());
            }
        } else {
            throw new Exception(response.getMessage());
        }
        return order;
    }

    @Override
    public void doPaymentQueryAndPayment() {
        //查询分账中的订单
        QueryWrapper<TOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id");
        queryWrapper.eq("order_status", 1);//订单支付成功
        queryWrapper.eq("profit_sharing", "Y");//需要分账
        queryWrapper.eq("profit_sharing_status", 1);//分账中
        queryWrapper.eq("deleted", 0);//未删除的
        List<TOrder> queryList = tOrderMapper.selectList(queryWrapper);
        if (queryList != null) {
            for (TOrder order : queryList) {
                //查询分账结果
                queryPayment(order.getId());
            }
        }

        //执行订单查询，进行分账
        QueryWrapper<TOrder> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.select("id");
        queryWrapper1.eq("order_status", 1);//订单支付成功
        queryWrapper1.eq("profit_sharing", "Y");//需要分账
        queryWrapper1.eq("profit_sharing_status", 0);//等待执行分账操作的
        queryWrapper1.eq("deleted", 0);//未删除的
        queryWrapper1.le("time_end", DateUtils.formatDate(DateUtils.getMinuteBeforeTime(60), "yyyyMMddHHmmss"));//一个小时以前的订单
        List<TOrder> orderList = tOrderMapper.selectList(queryWrapper1);
        if (orderList != null) {
            for (TOrder order : orderList) {
                //执行分账
                payment(order.getId());
            }
        }
    }

    @Override
    public IPage<TOrder> selectList(Integer pageNum, Integer pageSize, TOrder params, String code) {
        Page<TOrder> page = new Page<>(pageNum, pageSize);
        IPage<TOrder> resultIPage = tOrderMapper.selectListXml(page, params, code);
        return resultIPage;
    }

    @Override
    public List<TOrder> selectList(TOrder params, String code) {
        List<TOrder> list = tOrderMapper.selectListXml(params, code);
        return list;
    }

    //查询订单分账详情
    @Override
    public List<ReceiveRecord> selectPaymentByOrderId(Long id) {
        return receiverService.selectPaymentByOrderId(id);
    }

    @Override
    public TOrder selectByOutOrderNo(String outOrderNo) {
        QueryWrapper<TOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("out_order_no", outOrderNo);
        return tOrderMapper.selectOne(queryWrapper);
    }

    @Override
    public TOrder selectByOutTradeNo(String outTradeNo) {
        QueryWrapper<TOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("out_trade_no", outTradeNo);
        return tOrderMapper.selectOne(queryWrapper);
    }

    @Override
    public Map selectListStatistics(TOrder params, String code) {
        Map map = tOrderMapper.selectListStatisticsXml(params, code);
        if (map != null) {
            map.put("sumCount", map.get("sumCount") == null ? 0 : map.get("sumCount"));
            map.put("sumFee", map.get("sumFee") == null ? 0 : map.get("sumFee"));
            map.put("settlementFee", map.get("settlementFee") == null ? 0 : map.get("settlementFee"));
            map.put("couponTotalFee", map.get("couponTotalFee") == null ? 0 : map.get("couponTotalFee"));
            map.put("refundCount", map.get("refundCount") == null ? 0 : map.get("refundCount"));
            map.put("refundFee", map.get("refundFee") == null ? 0 : map.get("refundFee"));
            map.put("wxCount", map.get("wxCount") == null ? 0 : map.get("wxCount"));
            map.put("wxFee", map.get("wxFee") == null ? 0 : map.get("wxFee"));
            map.put("aliCount", map.get("aliCount") == null ? 0 : map.get("aliCount"));
            map.put("aliFee", map.get("aliFee") == null ? 0 : map.get("aliFee"));
            map.put("memberCount", map.get("memberCount") == null ? 0 : map.get("memberCount"));
            map.put("memberFee", map.get("memberFee") == null ? 0 : map.get("memberFee"));
            map.put("tytCount", map.get("tytCount") == null ? 0 : map.get("tytCount"));
            map.put("tytFee", map.get("tytFee") == null ? 0 : map.get("tytFee"));
            map.put("depositCount", map.get("depositCount") == null ? 0 : map.get("depositCount"));
            map.put("depositTotalFee", map.get("depositTotalFee") == null ? 0 : map.get("depositTotalFee"));
        }
        return map;
    }

    @Override
    public IPage<TOrder> selectMiniList(Integer pageNum, Integer pageSize, WxPay params) {
        Page<TOrder> page = new Page<>(pageNum, pageSize);
        QueryWrapper<TOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("merchant_id", params.getMerchantId());
        queryWrapper.eq("phone", params.getMobile());
        IPage<TOrder> resultIPage = tOrderMapper.selectPage(page, queryWrapper);
        return resultIPage;
    }


    @Override
    public TOrder payByBalance(String deviceNo, Long totalFee, Long memberFee, Long memberId, String outTradeNo, Long storeUserId) throws Exception {

        try {
            //获取设备信息
            Device device = deviceService.selectByDeviceNo(deviceNo);
            //获取门店信息
            Store store = storeService.getById(device.getStoreId());
            //获取商户信息
            Merchant merchant = merchantService.getById(store.getMerchantId());
            //修改会员余额
            Member member = memberService.getById(memberId);
            if (member.getTotalBalances() - memberFee < 0) {
                throw new Exception("余额不足");
            }
            Member upMembre = new Member();
            upMembre.setId(member.getId());
            upMembre.setTotalBalances(member.getTotalBalances() - memberFee);
            memberService.updateById(upMembre);

            String merchantCode = merchant.getCode();
            String[] codes = merchantCode.split("-");
            Long serviceId = Long.valueOf(codes[0]);//服务商ID
            Long agentId = Long.valueOf(codes[1]);//代理商ID

            TOrder order = new TOrder();
            //服务商，代理商，商户，门店信息
            order.setBusinessServiceId(serviceId);
            order.setAgentId(agentId);
            order.setMerchantId(merchant.getId());
            order.setMerchantName(merchant.getName());
            order.setStoreId(store.getId());
            order.setStoreName(store.getName());
            order.setCode(store.getCode());

            order.setOrderTotalFee(Long.valueOf(totalFee));
            order.setMemberTotalFee(Long.valueOf(memberFee));
            order.setSettlementTotalFee(0L);
            order.setCouponFee(0L);
            order.setPhone(member.getMobile());
            order.setOutTradeNo(outTradeNo);
            order.setPayType(3);
            order.setProfitSharing("N");
            order.setProfitSharingStatus(0);
            order.setTradeType("DEFAULT");//会员支付，默认类型
            order.setOpenid(member.getSubOpenId());//支付者信息
            //门店店员ID
            SysUser sysUser = sysUserService.getById(storeUserId);
            if (sysUser != null) {
                order.setOrderCreateUserName(sysUser.getUsername());
            }
            order.setStoreUserId(storeUserId);
            order.setDeviceNo(deviceNo);
            //支付成功
            order.setOrderStatus(1);
            order.setRealPayFee(memberFee);
            //结束时间
            order.setTimeEnd(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
            order.setUpdatedTime(new Date());
            //保存订单信息
            tOrderMapper.insert(order);

            //发送店员收款消息推送
            storeService.sendWxTempLateReceivables(order);
            //检查会员相关信息
            memberService.doMemberAccountChange(order.getMerchantId(), order.getId(), member, 2);

            return order;
        } catch (Exception e) {
            throw new Exception("余额支付失败");
        }
    }

    /**
     * 查询订单状态
     *
     * @param order
     * @return
     * @throws Exception
     */
    public TOrder queryOrderStatus(TOrder order, Integer times) throws Exception {
        try {
            //获取实时最新订单
            Merchant merchant = merchantService.getById(order.getMerchantId());
            //查询订单
            WxPayServiceExt wxPayService = weixinPayService.getServiceExt(order.getCode(), merchant.getSubMchId());
            WxPayOrderQueryRequest queryRequest = new WxPayOrderQueryRequest();
            queryRequest.setOutTradeNo(order.getOutTradeNo());
            WxPayOrderQueryResultExt resultExt = wxPayService.queryOrderExt(queryRequest);

            //处理订单查询结果
            if (WxPayConstants.ResultCode.SUCCESS.equals(resultExt.getReturnCode())//请求成功
                    && WxPayConstants.ResultCode.SUCCESS.equals(resultExt.getResultCode())) {//查询结果成功
                order.setTimeEnd(resultExt.getTimeEnd());
                //交易成功
                if (WxPayConstants.WxpayTradeStatus.SUCCESS.equals(resultExt.getTradeState())) {
                    //支付成功
                    order.setOrderStatus(1);
                    order.setSettlementTotalFee(resultExt.getSettlementTotalFee() == null || resultExt.getSettlementTotalFee() == 0 ? order.getMemberTotalFee() : Long.valueOf(resultExt.getSettlementTotalFee()));
                    order.setCouponFee(resultExt.getCouponFee() == null || resultExt.getCouponFee() == 0 ? 0L : Long.valueOf(resultExt.getCouponFee()));

                    order.setRealPayFee(Long.valueOf(resultExt.getCashFee()));
                    //修改订单状态
                    tOrderMapper.updateById(order);
                    //验证是否是会员，是否推送会员消息
                    Integer isSend = StringUtils.isNotBlank(resultExt.getSubIsSubscribe()) && resultExt.getSubIsSubscribe().equals("Y") ? 2
                            : StringUtils.isNotBlank(resultExt.getIsSubscribe()) && resultExt.getIsSubscribe().equals("Y") ? 1 : 0;

                    //发送店员收款消息推送
                    storeService.sendWxTempLateReceivables(order);

                    memberService.checkIsToMember(merchant.getId(), resultExt.getOpenid(), resultExt.getSubOpenid(), resultExt.getAttach(), isSend, order.getId(), "WXPAY");
                } else {
                    //交易失败
                    if (WxPayConstants.WxpayTradeStatus.USER_PAYING.equals(resultExt.getTradeState())) {

                        if (times <= 10) {
                            times++;
                            //二次查询，再次等待
                            Thread.sleep(3000);
                            this.queryOrderStatus(order, times);
                        }
                    }
                    //交易失败
                    if (WxPayConstants.WxpayTradeStatus.PAY_ERROR.equals(resultExt.getTradeState())) {
                        //支付失败
                        order.setOrderStatus(2);
                        //修改订单状态
                        tOrderMapper.updateById(order);
                    }
                }
            }
        } catch (WxPayException e) {
            throw new Exception(e.getErrCodeDes());
        } catch (Exception e) {
            throw new Exception("查询订单状态失败");
        }
        return order;
    }

    public TOrder queryDepositOrderStatus(TOrder order, Integer times) throws Exception {
        try {
            //获取实时最新订单
            Merchant merchant = merchantService.getById(order.getMerchantId());
            //查询订单
            WxPayServiceExt wxPayService = weixinPayService.getServiceExt(order.getCode(), merchant.getSubMchId());
            DepositOrderQueryRequest queryRequest = new DepositOrderQueryRequest();
            queryRequest.setOutTradeNo(order.getOutOrderNo());
            queryRequest.setSignType(WxPayConstants.SignType.HMAC_SHA256);
            DepositOrderQueryResponse depositorderquery = wxPayService.depositorderquery(queryRequest);

            //处理订单查询结果
            if (WxPayConstants.ResultCode.SUCCESS.equals(depositorderquery.getReturnCode())//请求成功
                    && WxPayConstants.ResultCode.SUCCESS.equals(depositorderquery.getResultCode())) {//查询结果成功
                order.setTimeEnd(depositorderquery.getTimeEnd());
                //交易成功
                if (WxPayConstants.WxpayTradeStatus.SUCCESS.equals(depositorderquery.getTradeState())) {

                    //支付成功
                    order.setOrderStatus(5);
                    order.setSettlementTotalFee(Long.valueOf(depositorderquery.getSettlementTotalFee()));
                    order.setRealPayFee(Long.valueOf(depositorderquery.getCashFee()));
                    order.setCouponFee(Long.valueOf(depositorderquery.getCouponFee()));
                    //修改订单状态
                    tOrderMapper.updateById(order);
                } else {
                    //交易失败
                    if (WxPayConstants.WxpayTradeStatus.USER_PAYING.equals(depositorderquery.getTradeState())) {

                        if (times <= 10) {
                            times++;
                            //二次查询，再次等待
                            Thread.sleep(3000);
                            this.queryOrderStatus(order, times);
                        }
                    }
                    //交易失败
                    if (WxPayConstants.WxpayTradeStatus.PAY_ERROR.equals(depositorderquery.getTradeState())) {
                        //支付失败
                        order.setOrderStatus(2);
                        //修改订单状态
                        tOrderMapper.updateById(order);
                    }
                }
            }
        } catch (WxPayException e) {
            throw new Exception(e.getErrCodeDes());
        } catch (Exception e) {
            throw new Exception("查询订单状态失败");
        }
        return order;
    }

    public Deposit queryDepositRefundStatus(Deposit deposit, Integer times) throws Exception {
        try {
            //获取实时最新订单
            Merchant merchant = merchantService.getById(deposit.getMerchantId());
            //查询押金支付
            WxPayServiceExt wxPayService = weixinPayService.getServiceExt(deposit.getCode(), merchant.getSubMchId());
            DepositRefundQueryRequest queryRequest = new DepositRefundQueryRequest();
            queryRequest.setOutRefundNo(deposit.getOutRefundNo());
            queryRequest.setSignType(WxPayConstants.SignType.HMAC_SHA256);
            DepositRefundQueryResponse depositrefundquery = wxPayService.depositrefundquery(queryRequest);

            //处理押金查询结果
            if (WxPayConstants.ResultCode.SUCCESS.equals(depositrefundquery.getReturnCode())//请求成功
                    && WxPayConstants.ResultCode.SUCCESS.equals(depositrefundquery.getResultCode())) {//查询结果成功
                deposit.setTimeEnd(depositrefundquery.getRefundSuccessTime());
                //交易成功
                if (WxPayConstants.WxpayTradeStatus.SUCCESS.equals(depositrefundquery.getRefundStatus())) {
                    //支付成功
                    deposit.setDepositStatus(1);
                    deposit.setRefundId(depositrefundquery.getRefundId());
                    deposit.setRefundRecvAccout(depositrefundquery.getRefundRecvAccout());
                    deposit.setDepositFee(Long.valueOf(depositrefundquery.getRefundFee()));
                    //修改订单状态
                    depositMapper.updateById(deposit);
                } else {
                    //交易失败
                    if (WxPayConstants.RefundStatus.CHANGE.equals(depositrefundquery.getRefundStatus())) {

                        if (times <= 10) {
                            times++;
                            //二次查询，再次等待
                            Thread.sleep(3000);
                            this.queryDepositRefundStatus(deposit, times);
                        }
                    }
                    //交易失败
                    if (WxPayConstants.RefundStatus.CHANGE.equals(depositrefundquery.getRefundStatus())) {
                        //支付失败
                        deposit.setDepositStatus(2);
                        //修改订单状态
                        depositMapper.updateById(deposit);
                    }
                }
            }
        } catch (WxPayException e) {
            throw new Exception(e.getErrCodeDes());
        } catch (Exception e) {
            throw new Exception("查询订单状态失败");
        }
        return deposit;
    }

    @Override
    public TOrder createScanPayOrder(String deviceNo, Integer totalFee, Integer memberFee, String phone, String outTradeNo, String openid, Integer payType, Long storeUserId) {

        //获取设备信息
        Device device = deviceService.selectByDeviceNo(deviceNo);
        //获取门店信息
        Store store = storeService.getById(device.getStoreId());
        //获取商户信息
        Merchant merchant = merchantService.getById(store.getMerchantId());

        String merchantCode = merchant.getCode();
        String[] codes = merchantCode.split("-");
        Long serviceId = Long.valueOf(codes[0]);//服务商ID
        Long agentId = Long.valueOf(codes[1]);//代理商ID

        TOrder order = new TOrder();
        //服务商，代理商，商户，门店信息
        order.setBusinessServiceId(serviceId);
        order.setAgentId(agentId);
        order.setMerchantName(merchant.getName());
        order.setStoreId(store.getId());
        order.setMerchantId(merchant.getId());
        order.setStoreName(store.getName());
        order.setCode(store.getCode());

        order.setOrderTotalFee(Long.valueOf(totalFee));
        //会员价格
        order.setMemberTotalFee(memberFee != null ? Long.valueOf(memberFee) : Long.valueOf(totalFee));
        if (StringUtils.isNotBlank(phone)) {
            order.setPhone(phone);
        }
        order.setOutTradeNo(outTradeNo);
        order.setPayType(payType);
        order.setProfitSharing("N");
        order.setProfitSharingStatus(0);
        order.setTradeType("SCAN");//扫码支付
        order.setOpenid(openid);//支付者信息
        SysUser sysUser = sysUserService.getById(storeUserId);
        if (sysUser != null) {
            order.setOrderCreateUserName(sysUser.getUsername());
        }
        order.setStoreUserId(storeUserId);
        order.setDeviceNo(deviceNo);
        //保存订单信息
        tOrderMapper.insert(order);
        return order;
    }


    /**
     * 根据订单，查询分账结果
     *
     * @param orderId
     */
    private void queryPayment(Long orderId) {

        //获取实时最新订单
        TOrder order = tOrderMapper.selectById(orderId);
        Merchant merchant = merchantService.getById(order.getMerchantId());
        if (order.getProfitSharingStatus() == 2) {
            return;
        }
        if (order.getProfitSharingStatus() == 3) {
            return;
        }
        //查询订单
        WxPayServiceExt wxPayService = weixinPayService.getServiceExt(order.getCode(), merchant.getSubMchId());
        PaymentQueryRequest request = new PaymentQueryRequest();
        //签名类型
        request.setSignType(WxPayConstants.SignType.HMAC_SHA256);
        request.setOutOrderNo(order.getOutOrderNo());
        request.setTransactionId(order.getTransactionId());
        try {
            PaymentQueryResponse response = wxPayService.profitsharingquery(request);
            //执行分账结果处理
            this.updateOrderPaymentStatus(response, order, merchant);
        } catch (WxPayException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据订单，执行分账
     *
     * @param orderId
     */
    @Transactional
    public void payment(Long orderId) {
        //获取实时最新订单
        TOrder order = tOrderMapper.selectById(orderId);
        if (order.getProfitSharingStatus() == 1) {
            return;
        }
        //查询商户信息
        Merchant merchant = merchantService.getById(order.getMerchantId());
        if (merchant == null) {
            return;
        }
        //查询分账接收方
        List<Receiver> receiverList = receiverService.selectByMerchantId(order.getMerchantId());
        if (receiverList == null || receiverList.size() <= 0) {
            return;
        }
        for (Receiver r : receiverList) {
            r.setAmount(Integer.valueOf(merchant.getPerDraw() + ""));
            r.setDescription("分账给供应商");
        }
        //查询订单
        WxPayServiceExt wxPayService = weixinPayService.getServiceExt(order.getCode(), merchant.getSubMchId());
        PaymentPostRequest request = new PaymentPostRequest();
        //签名类型
        request.setSignType(WxPayConstants.SignType.HMAC_SHA256);
        //微信支付订单号
        request.setTransactionId(order.getTransactionId());
        //分账单号
        String outOrderNo = System.currentTimeMillis() + "";
        request.setOutOrderNo(outOrderNo);
        //分账接收方
        request.setReceivers(JSON.toJSONString(receiverList));

        try {
            //执行分账操作申请
            PaymentPostResponse response = wxPayService.profitsharing(request);
            //处理分账！（请求）！结果
            if (WxPayConstants.RefundStatus.SUCCESS.equals(response.getReturnCode())
                    && WxPayConstants.ResultCode.SUCCESS.equals(response.getResultCode())) {

                //修改订单分账相关信息
                TOrder updateOrder = new TOrder();
                updateOrder.setId(order.getId());
                updateOrder.setOutOrderNo(outOrderNo);//商户分账单号
                updateOrder.setOrderId(response.getOrderId());//微信分账单号
                updateOrder.setProfitSharingStatus(1);//分帐中
                tOrderMapper.updateById(updateOrder);

                //添加商户分账记录
                for (Receiver receiver : receiverList) {
                    ReceiveRecord receiveRecord = new ReceiveRecord();
                    receiveRecord.setAmount(Long.valueOf(receiver.getAmount()));
                    receiveRecord.setCode(order.getCode());
                    receiveRecord.setOrderId(order.getId());
                    receiveRecord.setMerchantId(merchant.getId());
                    receiveRecord.setReceiverId(receiver.getId());
                    receiveRecord.setStatus(1);
                    receiveRecord.setOutOrderNo(outOrderNo);
                    receiveRecordService.save(receiveRecord);
                }
            }
        } catch (WxPayException e) {

            //修改订单分账相关信息
            TOrder updateOrder = new TOrder();
            updateOrder.setId(order.getId());
            updateOrder.setOutOrderNo(outOrderNo);//商户分账单号
            updateOrder.setProfitSharingStatus(3);//分帐中
            tOrderMapper.updateById(updateOrder);

            e.printStackTrace();
        }
    }

    /**
     * 根据分账查询状态，操作分账结果集
     *
     * @param response
     * @param order
     * @param merchant
     */
    @Transactional
    public void updateOrderPaymentStatus(PaymentQueryResponse response, TOrder order, Merchant merchant) {
        if (WxPayConstants.RefundStatus.SUCCESS.equals(response.getReturnCode())
                && WxPayConstants.ResultCode.SUCCESS.equals(response.getResultCode())) {

            TOrder updateOrder = new TOrder();
            updateOrder.setId(order.getId());

            if ("FINISHED".equals(response.getStatus())) {//订单处理完成
                updateOrder.setProfitSharingStatus(2);//分帐成功
                receiveRecordService.updateStatus(order.getOutOrderNo(), 2);
                //TODO 待优化，处理微信返回结果集
                Integer cs = receiveRecordService.selectCountByOutOrderNo(order.getOutOrderNo());
                merchant.setDrawFee(merchant.getDrawFee() + merchant.getPerDraw() * cs);
                merchantService.addOrUpdate(merchant);
            } else {
                updateOrder.setProfitSharingStatus(3);//分帐失败
                receiveRecordService.updateStatus(order.getOutOrderNo(), 2);
                log.error(order.getOutTradeNo() + "分账失败，已关单,返回原因：" + response.getCloseReason());
            }

            tOrderMapper.updateById(updateOrder);
        }
    }

    /**
     * 修改订单状态
     */
    private void updateOrderStatus(Long id, Long realConsumeFee) {
        TOrder torder = new TOrder();
        torder.setId(id);
        torder.setSettlementTotalFee(realConsumeFee);
        torder.setOrderStatus(1);
        tOrderMapper.updateById(torder);
    }
}